package com.ruoyi.im.websocket;

import java.net.URI;
import java.util.Map;

import org.apache.logging.log4j.util.Strings;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyInterceptor implements HandshakeInterceptor {

    /**
     * 握手前
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("握手开始");
        String hostName = request.getRemoteAddress().getHostName();
//        String sessionId = hostName+String.valueOf((int)(Math.random()*1000));
        String sessionId = null;

        URI uri = request.getURI();
        String query = uri.getQuery();
        if (Strings.isNotBlank(query)) {
            String[] split = query.split("&");
            for (String s : split) {
                String[] split1 = s.split("=");
                if (split1[0].equals("userId")) {
                    sessionId = split1[1];
                }
            }
        }

        if (sessionId == null) return false;

        if (Strings.isNotBlank(sessionId)) {
            // 放入属性域
            attributes.put("userId", sessionId);
            System.out.println("用户 userId " + sessionId + " 握手成功！");
            return true;
        }
        System.out.println("用户登录已失效");
        return false;
    }

    /**
     * 握手后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("握手完成");
    }

}
